import {changeSelectState, updateItemNum} from "@mall/api/shopCart";
import router from "@src/router";

Component({
  properties: {
    goods: {
      type: Object,
      value: {}
    },
    disable: {
      type: Boolean,
      value: false
    },
    showError: {
      type: Boolean,
      value: true
    }
  },
  observers: {
    goods: function (goods) {
      if (goods.skuInfo) {
        try {
          this.setData({
            skuList: JSON.parse(goods.skuInfo),
          })
          this.setData({num: goods.num, selected: goods.selected})
        } catch (e) {
          console.error(e)
        }
      }
    }
  },
  data: {
    skuList: [],
    timeoutId: null,
    selected: null,
    num: null,
  },
  methods: {
    toShopDetasils(){
      const self=this;
      router.push({
        name: "mall/goods-detail",
        success:function(res){
          res.eventChannel.emit('toGoodsDetailParams', {data:self.data.goods});
      }
      })
    },
    throttleEvent(data) {
      this.setData(data)
    },
    handleSelect(e) {
      if (this.data.disable) {
        return;
      }
      let selected = this.data.selected;
      this.setData({selected: !this.data.selected})
      let data = {
        cardItemIdList: [this.data.goods.cartItemId],
        selected: !selected
      }
      this.triggerEvent('updateSelect', {cartItemId: this.data.goods.cartItemId, selected: !selected});
      changeSelectState(data).then(res => {})
    },
    handleUpdateNum(e) {
      if (this.data.disable) {
        return;
      }
      let params = {
        cartItemId: this.data.goods.cartItemId,
        goodsId: this.data.goods.goodsId,
        num: e.detail.num,
        skuId: this.data.goods.skuId,
        storeId: this.data.goods.storeId
      }
      this.setData({num: params.num })
      this.triggerEvent('updateNum', {num: params.num, cartItemId: this.data.goods.cartItemId });
      updateItemNum(params).then(res => {
        // this.triggerEvent('update');
      }).catch(()=> {
        // 异常, 强制更新
        this.triggerEvent('update');
      })
    },

  }
});
